package com.thh.api;

import com.thh.service.DispatchService;
import com.rabbitmq.client.Channel;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

/**
 * @Author thh
 * @Description
 * @Version 1.0
 **/
@Component
public class OrderDispatchConsumber {

    private final Logger logger = LoggerFactory.getLogger(OrderDispatchConsumber.class);

    @Autowired
    private DispatchService dispatchService;


    // 接收队列消息
    @RabbitListener(queues = {"orderQueue"})
    public void messageConsumer(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag)
            throws Exception {
        try {

            //MQ 里面的数据转成JSON对象
            JSONObject orderInfo = JSONObject.fromObject(message);
            System.out.println("收到MQ里面的消息是：" + orderInfo.toString());
            //Thread.sleep(5000);
            //执行业务操作，同一个数据不能处理两次，根据业务情况去重，保证幂等性。
            String orderId = orderInfo.getString("orderId");

            /* if(!redisService.get(orderId)){
                return;
            };*/

           // redisService.setnx(orderId,100);//分布式锁  考虑并发问题

            //这里就是一个分配
            dispatchService.dispatch(orderId);
            System.out.println(1/0);
            //ack --告诉MQ,我已经收到消息了
            channel.basicAck(tag, false);
        } catch (Exception ex) {
            // 死信 + 重定向队列 + 报警
            ex.printStackTrace();
        }
    }
}
